from flask import Blueprint, jsonify, request
import json
from db import db1

bp_courses = Blueprint('courses', __name__)


def xtree(data):
    if not data:
        return data
    else:
        tree = {}
        list = []
        for i in data:
            tree[i['id']] = i
        for j in data:
            if j['pid'] == 0:
                list.append(j)
            else:
                if 'son' not in tree[j['pid']]:
                    tree[j['pid']]['son'] = []
                tree[j['pid']]['son'].append(j)
        return list


@bp_courses.route('/cate', methods=['POST', 'GET'])
def cate():
    if request.method == 'POST':
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form
        print(data)
        sql = '''insert into cates values (0,"%s",%d,%s)''' % (data['name'], int(data['pid']), data['params'])
        db1.update(sql)
        return jsonify({'code': 200})
    elif request.method == 'GET':
        sql = '''select * from cates'''
        res = db1.findall(sql)
        data = xtree(res)
        return jsonify({'code': 200, 'list': data})


@bp_courses.route('/pageM', methods=['GET'])
def pageM():
    if request.method == 'GET':
        capge = request.args.get('cpage')
        page_size = 3
        start = (int(capge) - 1) * page_size
        sql = 'select c.name,c.params,t.name as tname from cates as c left join cates as t on c.pid=t.id order by c.id asc limit %d,%d' % (
            start, page_size)
        sql2 = '''select count(id) from cates'''
        res = db1.findall(sql)
        total = db1.findone(sql2)
        return jsonify({'code': 200, 'list': res, 'total': total['count(id)']})
